import React from 'react';
import { Upload, Button, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { API_URL, getToken } from '../../utils/common';
import type { UploadProps } from 'antd';
import type { UploadPropsType } from './index.type';

const UploadComponent: React.FC<UploadPropsType> = ({
    maxCount = 1,
    showUploadList = true,
    uploadUrl = '/upload',
    typename = 'file',
    onUploadSuccess, 
}) => {
    const props: UploadProps = {
        name:typename,
        action: API_URL + uploadUrl,
        headers: {
            Authorization: getToken() || 'defaultTokenValue',
        },
        onChange(info) {
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            switch (info.file.status) {
                case 'done':
                    message.success(`${info.file.name} file uploaded successfully`);
                    if (onUploadSuccess && info.file.response && info.file.response.data && info.file.response.data.url) {
                        onUploadSuccess(info.file.response.data.url); // 调用回调函数
                    }
                    if (onUploadSuccess && info.file.response && info.file.response.data && info.file.response.data.image) {
                        onUploadSuccess(info.file.response.data.image); // 调用回调函数
                    }
                    break;
                case 'error':
                    message.error(`${info.file.name} file upload failed.`);
                    break;
                default:
                    break;
            }
        },
    };

    return (
        <Upload {...props} maxCount={maxCount} showUploadList={showUploadList}>
            <Button icon={<UploadOutlined />}>上传</Button>
        </Upload>
    );
};

export default UploadComponent;
